<?php

class prestashop{

    public $sitelink;
    public $checklink=false;
    private $url;
    private $key="mmdreamisok";

    public function __construct($param=array())
    {
        $this->sitelink=$param["domian"];
        $this->url=$this->sitelink."/webservice/hiapi.php";
        $this->checklink();
    }

    public function change_site($site)
    {
        $this->sitelink=$site["domian"];
        $this->url=$this->sitelink."/webservice/hiapi.php";
        $this->checklink();
    }

    public function doaction($post)
    {
        $post["action"]="doaction";
        $result=$this->sendrequest($post);
        return $result;
    }

    public function fixcombine($product)
    {
        $product["action"]="fixcombine";
        $result=$this->sendrequest($product);
        return $result;
    }

    public function syncdesc($post)
    {
        $post["action"]="syncdesc";
        $result=$this->sendrequest($post);
        return $result;
    }

    public function syncimages($post)
    {
        $post["action"]="syncimages";
        $result=$this->sendrequest($post);
        return $result;
    }

    public function opprice($post)
    {
        $post["action"]="opprice";
        $result=$this->sendrequest($post);
        return $result;
    }

    public function opprice2($post)
    {
        $post["action"]="opprice2";
        $result=$this->sendrequest($post);
        return $result;
    }

    public function getopprice($post)
    {
        $post["action"]="getopprice";
        $result=$this->sendrequest($post);
        return $result;
    }

    public function getorderinfo($post)
    {
        $post["action"]="orderinfo";
        $result=$this->sendrequest($post);
        $result=json_decode($result,true);

        if($result["data"]){
            $order=$result["data"];
            $utcDate = date('Y-m-d\TH:i:s\Z',strtotime($order["date_add"]));
            $order["date_add"] = date('Y-m-d H:i:s',strtotime($utcDate)+60*60*5);
            foreach($order["products"] as &$item)
            {
                $item["handler"]="/home/".$item["product_id"]."-xx.html";
            }
            return $order;
        }
        return false;
    }

    public function getopprice2($post)
    {
        $post["action"]="getopprice2";
        $result=$this->sendrequest($post);
        return $result;
    }

    public function syncorder($page,$maxoid,$status=1)
    {
        $param=["action"=>"syncorder","page"=>$page,"maxoid"=>0];
        $result=$this->sendrequest($param);
        $result=json_decode($result,true);

        if($result["data"]){
            foreach($result["data"] as &$order)
            {
                $utcDate = date('Y-m-d\TH:i:s\Z',strtotime($order["date_add"]));
                $order["date_add"] = date('Y-m-d H:i:s',strtotime($utcDate)+60*60*5);
                foreach($order["products"] as &$item)
                {
                    /*
                    if(strstr($item," - "))
                    {
                        $tmp=explode(" - ",$item["product_name"]);
                        $item["variant"]=str_replace($tmp[0]." - ","",$item["product_name"]);
                        $item["product_name"]=$tmp[0];    
                    }
                    else
                    {
                        $item["variant"]="";
                    }
                    */
                    $item["handler"]="/home/".$item["product_id"]."-xx.html";
                }
            }
        }
        return $result;
    }

    public function checkwaitorder($olist)
    {
        $param=["action"=>"checkwaitorder","data"=>$olist];
        $result=$this->sendrequest($param);
        $result=json_decode($result,true);
        return $result;
    }

    public function cancel($oid)
    {
        $param=["action"=>"cancel","oid"=>$oid];
        $result=$this->sendrequest($param);
        return $result;
    }
    public function refresh($oid)
    {

        $param=["action"=>"refresh","oid"=>$oid];
        $result=$this->sendrequest($param);
        return $result;
    }


    public function shiporder($oid,$trackingnum,$newship=0)
    {
        $param=["action"=>"shiporder","oid"=>$oid,"trackingnum"=>$trackingnum];
        $result=$this->sendrequest($param);
        return $result;
    }

    public function upimage($post)
    {
        $post["action"]="updateimagetonew";
        $result=$this->sendrequest($post);

        echo $result;
        die();
        return $result;
    }

    public function syncuser($page,$maxuid)
    {
        $param=["action"=>"syncuser","page"=>$page,"maxuid"=>$maxuid];
        $result=$this->sendrequest($param);
        $result=json_decode($result,true);
        return $result;
    }

    public function delproduct($product)
    {
        $param=["action"=>"delproduct","rid"=>$product["rid"]];
        $result=$this->sendrequest($param);        
        return $result;
    }


    public function updatepro($rid,$param)
    {
        $param["rid"]=$rid;
        $param["action"]="updateproduct";
        $result=$this->sendrequest($param);
        return $result;
    }

    public function updateporder($order)
    {

    }

    public function addproduct($product)
    {
        $product["action"]="addproduct";
        $product["name"]=str_replace(["=","#",";",">","<","{","}","^"],"",$product["name"]);
        if(strlen($product["name"])>128)
        {
            $product["name"]=substr($product["name"],0,128);
        }        
        if(isset($product["option"]["vv"]))
        {
            foreach($product["option"]["vv"] as &$option)
            {
                foreach($option["value"] as &$val)
                {
                    $val=str_replace([">","<"],["&gt;","&lt;"],$val);
                }
            }
        }
        $product["desc"]=$this->cleanhtml($product["desc"]);

        $result=$this->sendrequest($product);
        if(substr($result,0,5)!='{"id"')
        {
            $this->savelog("radd:",$product);
            $this->savelog($result);
        }
        $result=json_decode($result,true);
        return ["rid"=>$result["id"],"url"=>$result["url"]];
    }

    public function delcatgory($cat)
    {
        $param=["action"=>"delcat","cat"=>$cat];
        $result=$this->sendrequest($param);
        $result=json_decode($result,true);
        return $result;
    }

    public function combinepricepro()
    {
        $param=["action"=>"combinepricepro"];
        $result=$this->sendrequest($param);
        $result=json_decode($result,true);
        return $result;
    }

    public function fixcombineprice($param)
    {
        $param["action"]="fixcombineprice";
        $result=$this->sendrequest($param);
        $result=json_decode($result,true);
        return $result;
    }

    public function rebuiltcombine($post)
    {
        $post["action"]="rebuiltcombine";
        $result=$this->sendrequest($post);
        return $result;
    }
    
    public function synccatrgory($category)
    {
        $param=["action"=>"synccat","categorys"=>$category];
        $result=$this->sendrequest($param);
        $result=json_decode($result,true);
        return $result;
    }

    private function checklink()
    {
        
        $reuslt=$this->sendrequest();
        if($reuslt=="dreamisok")
        {
            $this->checklink=true;
        }
    }

    private function sendrequest($param=[])
    {
        if(!isset($param["askey"]))
        {
            $param["askey"]=$this->key;
        }

        if(!isset($param["action"]))
        {
            $param["action"]="test";
        }
        switch($param["action"])
        {
            case "test":
                break;
            case "fixcombine";
            case "addproduct":
            case "updateproduct":
            case "delproduct":
            case "synccat":
            case "updatecat":
            case "delcat":
            case "syncuser":
            case "doaction":
            case "syncorder":
            case "orderinfo":
            case "shiporder":
            case "refresh":
            case "cancel":
            case "updateporder":
            case "checkwaitorder":
            case "updateimagetonew":
            case "combinepricepro":
            case "fixcombineprice":
            case "opprice":
            case "opprice2":
            case "getopprice":
            case "getopprice2":
            case "rebuiltcombine":
            case "syncimages":
            case "syncdesc":
                if(!$this->checklink)
                {
                    return "broken link";
                }
                break;
            default:
                return false;
        }
        
        return $this->curl($param);
    }

    private function cleanhtml($html)
    {
        $events = 'onmousedown|onmousemove|onmmouseup|onmouseover|onmouseout|onload|onunload|onfocus|onblur|onchange';
        $events .= '|onsubmit|ondblclick|onclick|onkeydown|onkeyup|onkeypress|onmouseenter|onmouseleave|onerror|onselect|onreset|onabort|ondragdrop|onresize|onactivate|onafterprint|onmoveend';
        $events .= '|onafterupdate|onbeforeactivate|onbeforecopy|onbeforecut|onbeforedeactivate|onbeforeeditfocus|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onmove';
        $events .= '|onbounce|oncellchange|oncontextmenu|oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondeactivate|ondrag|ondragend|ondragenter|onmousewheel';
        $events .= '|ondragleave|ondragover|ondragstart|ondrop|onerrorupdate|onfilterchange|onfinish|onfocusin|onfocusout|onhashchange|onhelp|oninput|onlosecapture|onmessage|onmouseup|onmovestart';
        $events .= '|onoffline|ononline|onpaste|onpropertychange|onreadystatechange|onresizeend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onsearch|onselectionchange';
        $events .= '|onselectstart|onstart|onstop';
        $preg = "/<[\s]*script[\s\S](.*?)script[\s]*>/ims";    
        $html = preg_replace($preg,"",$html);
        $html = preg_replace("/<(object.*?)>(.*?)<(\/object.*?)>/si","",$html);
        $html = preg_replace("/<(kse.*?)(.*?)(\/kse:widget.*?)>/si","",$html);
        $html = preg_replace("/\s(style)=['\"].*?['\"]/si","",$html);
        $preg = '/\s(' . $events . ')=".*?"/is';
        $html = preg_replace($preg," ",$html);
        $preg = '/\s(' . $events . ')=\'.*?\'/is';
        $html = preg_replace($preg," ",$html);
        $html = str_replace('javascript:void(0);','',$html);

        return $html;
    }

    private function savelog($msg,$datainfo=[])
    {
        $rawmsg="-----time:".date("H:i:s")."---------\n";
        $rawmsg.=$msg."\n";
        if($datainfo) $rawmsg.=json_encode($datainfo)."\n\n";
        if(!file_exists("./logs/".date("Ymd")."prestashop.text"))
        {
			file_put_contents("./logs/".date("Ymd")."prestashop.text","newfile\n",FILE_APPEND | LOCK_EX);
        	chown("./logs/".date("Ymd")."prestashop.text","www");
        }
        file_put_contents("./logs/".date("Ymd")."prestashop.text",$rawmsg,FILE_APPEND | LOCK_EX);
    }

    
    private function curl($param)
    {
        
        $data_string=json_encode($param,JSON_UNESCAPED_UNICODE);
        $ch = curl_init($this->url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string)
        ));
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            //print curl_error($ch);
        }
        curl_close($ch);
        return $result;
    }

}
